package office.stock.endpoints;

import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import office.stock.messaging.SubscribersRegistry;
import office.stock.messaging.WebsocketSubscriber;
import office.stock.messaging.notifications.ImageStoredNotification;
import office.stock.services.ImageStorage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Singleton
@ServerEndpoint("/offers")
public class OffersEndpoint {
    private final static Log log = LogFactory.getLog(OffersEndpoint.class);

    @EJB
    private SubscribersRegistry subscribersRegistry;
    @EJB
    private ImageStorage imageStorage;
    
    @OnOpen
    public void onOpen(Session session) {
	log.info("Client initiated connection. Session id is " + session.getId());
	subscribersRegistry.addSubscriber(new WebsocketSubscriber(session));
    }
    
    @OnMessage
    public String onMessage(String message, Session session) {
	String serverMessage = "Handling message [" + message + "]";
	log.debug(serverMessage + " from client with session id " + session.getId());
	return serverMessage;
    }
    
    @OnMessage
    public void onBinaryMessage(byte[] data, Session session) {
	log.debug("Got binary data");
	String id = imageStorage.store(data);
	ImageStoredNotification notification = new ImageStoredNotification(id);
	session.getAsyncRemote().sendText(notification.toString());
    }
    
    @OnClose
    public void onClose(CloseReason reason, Session session) {
	log.info("Client closed connection with session id " + session.getId());
	subscribersRegistry.removeSubscriber(session.getId());
    }
    
    @OnError
    public void onError(Throwable exception, Session session) {
	log.error("Error ocurred, session id is " + session.getId(), exception);
    }
}
